package com.fingard.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import com.fingard.text.StringHelper;
import com.fingard.xml.XElement;

import com.fingard.FGBiz;

public class ConnSet {

	public String dbDriver;
	public String dbUrl;
	public String dbUser;
	public String dbPassword;
	
	public boolean useJndi = false;
	public String useJndiProviderUrl;
	public String useJndiFactory;
	public String useJndiName;

	
	public void fromXElement(XElement p_XE) throws Exception{
		dbDriver = FGBiz.cipher.getFromXeAsStr(p_XE.getSingleChild("dbDriver"));//p_XE.getSingleTextNotNull("dbDriver");
		dbUrl = FGBiz.cipher.getFromXeAsStr(p_XE.getSingleChild("dbUrl"));//p_XE.getSingleTextNotNull("dbUrl");
		dbUser = FGBiz.cipher.getFromXeAsStr(p_XE.getSingleChild("dbUser"));//p_XE.getSingleTextNotNull("dbUser");
		dbPassword = FGBiz.cipher.getFromXeAsStr(p_XE.getSingleChild("dbPassword"));//p_XE.getSingleTextNotNull("dbPassword");
		useJndi = FGBiz.cipher.getFromXeAsBool(p_XE.getSingleChild("useJndi"));//p_XE.getSingleTextNotNull("useJndi")
		useJndiProviderUrl = FGBiz.cipher.getFromXeAsStr(p_XE.getSingleChild("useJndiProviderUrl"));//p_XE.getSingleTextNotNull("useJndiProviderUrl");
		useJndiFactory = FGBiz.cipher.getFromXeAsStr(p_XE.getSingleChild("useJndiFactory"));//p_XE.getSingleTextNotNull("useJndiFactory");
		useJndiName = FGBiz.cipher.getFromXeAsStr(p_XE.getSingleChild("useJndiName"));//p_XE.getSingleTextNotNull("useJndiName");
	}
	
	public Connection getConnection() throws Exception{
		Connection conn=null;
		
		if(useJndi){
			Context initCtx = null;
			DataSource ds = null;
			
			if(StringHelper.isNullOrEmpty(useJndiFactory)){
				try{
					initCtx = new InitialContext();
					ds = (javax.sql.DataSource) initCtx.lookup(useJndiName);
				}catch(NamingException e){
					e.printStackTrace();
					initCtx = new InitialContext();
					ds = (javax.sql.DataSource) initCtx.lookup("java:/comp/env/" + useJndiName);
				}
			}
			else{
				Hashtable<String,String> ht = new Hashtable<String,String>();
				ht.put(Context.INITIAL_CONTEXT_FACTORY, useJndiFactory);
				ht.put(Context.PROVIDER_URL, useJndiProviderUrl);
	        
				initCtx = new InitialContext(ht);
	            ds = (javax.sql.DataSource) initCtx.lookup(useJndiName);
			}
	        conn = ds.getConnection();//建立连接
	        
		}
		else{
			Class.forName(dbDriver);
			if(dbDriver.contains("sqlite") && StringHelper.isNullOrEmpty(dbUser)){
				conn=DriverManager.getConnection(dbUrl);
			}else{
				conn=DriverManager.getConnection(dbUrl, dbUser, dbPassword);
			}
		}
		return conn;
	}
}
